package com.corpgovernment.common.aspect;

import com.corpgovernment.common.annotation.SetQueryTraceId;
import com.corpgovernment.common.holder.TraceIdHolder;
import com.ctrip.corp.obt.generic.constants.GenericConstants;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @author zl.cui
 * @date 2023/11/20
 */
@Component
@Slf4j
@Order(Integer.MAX_VALUE)
public class SetQueryParamAdapter extends HandlerInterceptorAdapter  {

    private static final String RESPONSE_HEADER_QUERY_TRACE_ID_PREFIX = "query-trace-id";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        Method method = ((HandlerMethod) handler).getMethod();
        SetQueryTraceId annotation = method.getAnnotation(SetQueryTraceId.class);
        // 如果有traceId，则将X-Request-Id复制到response header
        if (annotation == null) {
            return true;
        }
        if (annotation.unset()){
            Cookie cookie = new Cookie(RESPONSE_HEADER_QUERY_TRACE_ID_PREFIX, StringUtils.EMPTY);
            // 将cookie的过期时间设置为0
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            return true;
        }

        String carryParam = response.getHeader(GenericConstants.X_REQUEST_ID);
        if (StringUtils.isBlank(carryParam)){
            carryParam = UUID.randomUUID().toString();
        }
        TraceIdHolder.setTraceId(carryParam);
        Cookie cookie = new Cookie(RESPONSE_HEADER_QUERY_TRACE_ID_PREFIX, carryParam);
        cookie.setMaxAge(1800); // 设置Cookie的有效期为半个小时
        cookie.setPath("/");
        response.addCookie(cookie); // 将Cookie保存到响应中
        return true;
    }
}
